package org.grow.auth.service;

import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.auth.dao.UserInfoRepository;

import org.grow.auth.entity.*;
import org.grow.auth.entity.QRoleInfo;
import org.grow.auth.entity.QUserInfo;
import org.grow.auth.entity.QUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/13
 */

@Service
public class UserInfoService implements UserDetailsService {
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;



    QUserInfo u = QUserInfo.userInfo;
    QRoleInfo r = QRoleInfo.roleInfo;
    QUserRole ur = QUserRole.userRole;

    @Override
    public UserDetails loadUserByUsername(String s)
            throws UsernameNotFoundException {
        System.out.println("登录进行到第二步，开始查询: "+s);
        UserInfo info = userInfoRepository.findByUsername(s);
        System.out.println("登录进行到第二步，查询结果: "+info);
        if (null == info){
            throw new UsernameNotFoundException("用户名未找到");
        }

        /**
         * select r.* from UserInfo u
         * inner join UserRole ur on u.userId=ur.userFk
         * inner join RoleInfo r on ur.roleFk = r.roleId
         * where  u.username = 'yangshu05'
        * */


        List<RoleInfo> roleInfos = jpaQueryFactory.select(r).from(u)
                .innerJoin(ur).on(u.userId.eq(ur.userFk))
                .innerJoin(r).on(ur.roleFk.eq(r.roleId))
                .where(u.username.eq(s))
                .fetch();
//        为了其他模块能够不依赖roleInfo类仍然能够获取角色
        List<SimpleGrantedAuthority> list = roleInfos.stream().map(x -> {
            return new SimpleGrantedAuthority(x.getAuthority());
        }).collect(Collectors.toList());

        info.setAuthorities(list);


        UserDetails build = User.withUserDetails(info).build();
        System.out.println("登录进行到第二步，格式化结果: "+build +"  "+build.getClass());

        return build;
    }
}
